package com.one.login.service.impl;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.one.login.common.RedisUtil;
import com.one.login.mapper.UserMapper;
import com.one.login.pojo.vo.LoginTicket;
import com.one.login.pojo.vo.User;
import com.one.login.pojo.vo.common.ResultMap;
import com.one.login.service.UserService;
import com.one.login.util.Util;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private HttpSession session;

	@Autowired
	private HttpServletResponse response;

	@Override
	public User selectOneById(String userId) {
		// TODO Auto-generated method stub
		return userMapper.selectOneById(userId);
	}

	@Override
	public Object getLoginUserInfo(String st) {
		// TODO Auto-generated method stub
		LoginTicket loginTicket = redisUtil.getObject(LoginTicket.class, "one-login", st);
		if (loginTicket == null) {
			return ResultMap.instance().setResultValues(false, 0, "");
		} else {
			return ResultMap.instance().setResultValues(loginTicket.getUser());
		}
	}

	@Override
	public void login(String username, String password) {
		// TODO Auto-generated method stub
		String id = DigestUtils.md5Hex(username);
		userMapper.login(id, username, password);
		try {
			String st = Util.UUID();
			LoginTicket loginTicket = new LoginTicket();
			loginTicket.setUser(new User(id, username));
			redisUtil.setObject(LoginTicket.class, loginTicket, "one-login", st);
			String url = (String) session.getAttribute("url");
			System.out.println("url--" + url);
			
			session.setAttribute("st", st);
			session.setAttribute("userId", id);
			response.sendRedirect(url + "?st=" + st);
			return;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return;
	}

}
